package component.action;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import component.Action;
import data.VersionTable;
import dto.Protocol;
import pojo.Merchant;
import service.MerchantService;
import vo.MerchantVO;

@Component("messageAction")
public class MessageAction implements Action<Protocol>{
	
	private final static Logger logger = LogManager.getLogger(MessageAction.class);
	
	@Resource(name="merchantService")
	private MerchantService manager;
	@Resource(name="versionTable")
	private VersionTable versionTable;
	
	

	@Override
	public void action(Protocol protocol) {
		Merchant merchant = new Merchant(null,protocol.getName(),protocol.getIdCard(),protocol.getAvatar(),protocol.getAddress(),Merchant.WAIT_AUDIT);
		logger.info(protocol);
		if (protocol.getOperater().equals(Protocol.REGISTER)) {
			logger.info("add:"+protocol.getName());
			merchant.setUpdateTime(new Date());
			Merchant m = manager.add(merchant);
			if (m != null) {
				versionTable.put(VersionTable.AUDIT_VERSION,System.currentTimeMillis() );
			}else{
				logger.warn("insert error"+merchant);
			}
		}
		if (protocol.getOperater().equals(Protocol.MODIFY)) {
			Merchant merchant2 = manager.getByName(merchant.getName()).get(0);
			if (merchant2!=null) {
				boolean isSuccess = Merchant.WHITE_LIST.equals(merchant2.getStatus())||Merchant.WHITE_LIST.equals(merchant2.getStatus());
				if (isSuccess) {
					logger.info("modify fail,ready success:"+merchant.toString());
				}else{
					merchant.setStatus(Merchant.WAIT_AUDIT);
					merchant.setUpdateTime(new Date());
					Merchant m = manager.updateByName(merchant);
					if (m != null) {
						versionTable.put(VersionTable.AUDIT_VERSION,System.currentTimeMillis() );
						logger.info("modify success:"+merchant);
					}else{
						logger.info("modify fail:"+merchant);
					}
				}
			
			}
			
		}
	}

}
